package model

import (
	"database/sql"
	"gpt-api/framework/db"
	"time"
)

type Events struct {
	db.BaseModel
	Title       string       `json:"title" gorm:"column:title;type:varchar(150);not null;comment:事件标题"`
	EventTypeID int          `json:"event_type_id" gorm:"column:event_type_id;type:int;not null;comment:事件类型id"`
	Content     string       `json:"content" gorm:"column:content;type:text;not null;comment:事件内容"`
	StartTime   *time.Time   `json:"start_time" gorm:"column:start_time;type:timestamptz;not null;comment:开始时间"`
	EndTime     *time.Time   `json:"end_time" gorm:"column:end_time;type:timestamptz;comment:结束时间"`
	Location    string       `json:"location" gorm:"column:location;type:varchar(150);default:'';comment:地点"`
	UserID      uint         `json:"user_id" gorm:"column:user_id;type:int;default:0;comment:用户ID"`
	MemberID    uint         `json:"member_id" gorm:"column:member_id;type:int;default:0;comment:所属成员ID"`
	EventType   EventType    `gorm:"foreignKey:ID;references:EventTypeID"`
	EventImages []EventImage `gorm:"foreignKey:EventID;references:ID"`
}

func (Events) TableName() string {
	return "events"
}

// 根据用户ID,成员ID统计事件数量
func (m Events) GetEventCountByUserIdAndMemberId(database *db.DB, userId uint64, memberId uint64) int64 {
	var count int64
	database.Model(&Events{}).Where("user_id = ? and member_id = ?", userId, memberId).Count(&count)
	return count
}

// 根据用户ID,成员ID获取事件列表,按开始时间倒序
func (m Events) GetEventsByUserIdAndMemberId(database *db.DB, userId uint64, memberId uint64, page int, size int) ([]Events, error) {
	var events []Events
	if page <= 0 {
		page = 1
	}
	if size <= 0 {
		size = 10
	}
	err := database.Model(&Events{}).Preload("EventType").Preload("EventImages").Where("user_id = ? and member_id = ?", userId, memberId).Offset((page - 1) * size).Limit(size).Order("start_time DESC").Find(&events).Error
	return events, err
}

// 根据ID获取事件
func (m Events) GetEventById(database *db.DB, id uint) (Events, error) {
	var event Events
	err := database.Where("id", id).Preload("EventImages").First(&event).Error
	return event, err
}

// 根据事件类型ID,用户ID获取事件
func (m Events) GetEventsByEventTypeIdAndUserId(database *db.DB, eventTypeId uint, userId uint) ([]Events, error) {
	var events []Events
	err := database.Where("event_type_id = ? and user_id = ?", eventTypeId, userId).Preload("EventImages").Find(&events).Error
	return events, err
}

// 根据事件类型ID,用户ID,删除事件
func (m Events) DeleteEventByEventTypeIdAndUserId(database *db.DB, Id uint, userId uint) error {
	// 开启事务
	tx := database.Begin()
	err := tx.Where("id", Id).Where("user_id", userId).Delete(&Events{}).Error
	if err != nil {
		tx.Rollback() // 事务回滚
		return err
	}

	// 如果删除出生事件,同步设置成员生日为空
	if m.EventTypeID == 1 {
		member := Member{
			Birthday: sql.NullTime{Time: time.Time{}, Valid: false},
		}
		member.ID = uint64(m.MemberID)
		err := tx.Model(member).Updates(map[string]interface{}{"birthday": member.Birthday}).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}
	}

	// 提交事务
	tx.Commit()

	return nil
}

// 添加OR更新事件
func (m Events) AddOrUpdateEvent(
	database *db.DB,
	event Events,
	images []string,
) error {
	// 开启事务
	tx := database.Begin()

	// 如果传入ID，则更新
	if m.ID != 0 {
		err := tx.Model(&Events{}).Where("id", m.ID).Updates(m).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}

		// 清理图片数据
		if err := tx.Where("event_id = ?", m.ID).Delete(&EventImage{}).Error; err != nil {
			tx.Rollback() // 事务回滚
			return err
		}
	} else {
		// 创建事件
		err := tx.Create(&m).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}
	}

	// 批量添加图片
	if len(images) > 0 {
		for _, image := range images {
			eventImage := EventImage{
				EventID:  uint(m.ID),
				ImageUrl: image,
				MemberID: m.MemberID,
				UserID:   m.UserID,
			}
			err := tx.Create(&eventImage).Error
			if err != nil {
				tx.Rollback() // 事务回滚
				return err
			}
		}

	}

	// 如果创建事件,同步设置成员生日为事件开始时间
	if m.EventTypeID == 1 {
		member := Member{
			Birthday: sql.NullTime{Time: *m.StartTime, Valid: true},
		}
		member.ID = uint64(m.MemberID)
		err := tx.Model(member).Updates(map[string]interface{}{"birthday": member.Birthday}).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}
	}

	// 提交事务
	tx.Commit()
	return nil
}
